/**
 * Created by root on 2015/1/13.
 */

var mongoose = require('mongoose');
var Category = mongoose.model('Category');
var async = require('async');

function CategoryService(){

}

CategoryService.prototype.loadData = function (pid, callback) {
    Category.find({
        parent: pid
    }).exec(function (err, categorys) {
        if (err) throw err;
        var data = [];
        for(var i= 0,len=categorys.length;i<len;i++){
            var d = {};
            d['cid'] = categorys[i].get('_id');
            d['text'] = categorys[i].get('text');
            d['isParent'] = true || !categorys[i].get('leaf');
            var parent = categorys[i].get('parent');
            d['pid'] = parent ? parent.id : undefined;
            data.push(d);
        }
        callback && callback(err, data);
    });
}

CategoryService.prototype.addNode = function (pid, callback) {
    var category = new Category();
    category['text'] = '新节点';
    category['leaf'] = true;
    category.parent = pid;
    Category.findByIdAndUpdate(pid, {
        leaf: false
    }, function (err, data1) {
        if(err) throw err;
        category.save(function (err, data2) {
            if(err) throw err;
            category['isParent'] = false;
            callback && callback(err, category);
        });
    })
};

CategoryService.prototype.removeNode = function (cid, callback) {
    var top = this;
    Category.findByIdAndRemove(cid, function (err, data) {
        if(err) throw err;
        Category.find({
            parent: cid
        }, function(err, data2){
            if(err) throw err;
            async.eachSeries(data2, function (item, callback) {
                top.removeNode(item.get('_id'), callback);
            }, function(err){
                if(err) throw err;
                callback && callback(err, data);
            });

        })
    })
};

CategoryService.prototype.renameNode = function (cid, text, callback) {
    Category.findByIdAndUpdate(cid, {
        text: text
    },function (err, data) {
        if(err) throw err;
        callback && callback(err, data);
    });
};

module.exports = CategoryService;